﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using ICSharpCode.TextEditor.Document;
using ICSharpCode.TextEditor;
using System.Diagnostics;
using System.IO;
using System.Drawing.Drawing2D;
using System.Reflection;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace UnrealDebugger.Panels
{
	public partial class FindPanel : Panel
	{
		public FindPanel()
            : base()
		{
			InitializeComponent();
		}

        public void FocusInput()
        {
            this.textBoxLookFor.SelectAll();
            this.textBoxLookFor.Focus();
        }

        public void FocusResults(FindResults results)
        {
            results.FocusResults();
            results.Show(this.dockPanelResults);
        }

        public FindResults GetResults()
        {
            return this.dockPanelResults.ActiveDocument as FindResults;
        }

        public FindResults GetNextResults()
        {
            bool getNextDocument = false;

            if (this.dockPanelResults.ActiveDocumentPane != null)
            {
                for (int x = 0; x < this.dockPanelResults.ActiveDocumentPane.Contents.Count; x++)
                {
                    DockContent dockContent = (DockContent)this.dockPanelResults.ActiveDocumentPane.Contents[x];

                    if (dockContent == this.dockPanelResults.ActiveDocumentPane.ActiveContent) { getNextDocument = true; }
                    else if (getNextDocument) { return (FindResults)dockContent; }
                }

                if (this.dockPanelResults.ActiveDocumentPane.Contents.Count > 0)
                {
                    return (FindResults)this.dockPanelResults.ActiveDocumentPane.Contents[0];
                }
            }

            return null;
        }

        private void FindAndHighlight(string text, bool matchCase, bool matchWholeWord)
        {
            this.SuspendLayout();

            FindResults results = new FindResults(
                text, 
                matchCase,
                matchWholeWord);

            results.OnHighlightColorChanged += new FindResults.HighlightColorChangedDelegate(OnHighlightColorChanged);
            results.Show(this.dockPanelResults);

            this.ResumeLayout();
        }

        private void OnHighlightColorChanged(Color color)
        {
            this.dockPanelResults.Refresh();
        }

        private void txtLookFor_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                FindAndHighlight(this.textBoxLookFor.Text, this.checkBoxMatchCase.Checked, this.checkBoxMatchWholeWord.Checked);
            }
        }
	}
}
